from flask import Blueprint, request
from toutiao.model.db_routing import Channel, db, UserChannel

channel_api = Blueprint('channel', __name__, url_prefix='/channel')


@channel_api.route('/follow_channel', methods=['POST'])
def channel_follow():
    """
    用户关注频道
    :return:
    """
    user_id = request.form.get('id')
    channel_id = request.form.get('channel')
    allow = Channel.query.filter_by(id=channel_id).first()

    if allow:

        chan = UserChannel.query.filter_by(user_id=user_id, channel_id=channel_id).first()
        if not chan:
            # 加一条
            rela = UserChannel(user_id=user_id, channel_id=channel_id, is_deleted=0)
            db.session.add()

            return {'code': '200', 'msg': '用户关注频道成功'}

        else:
            chan.is_deleted = 0
            db.session.commit()
            return {'code': '200', 'msg': '用户关注频道'}
    else:

        return {'msg': '频道已删除，不能关注'}
